package com.ctyun.city;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;

/**
 * @author yangjiming
 * @create 2021-04-17 23:28
 */
public class GetCityTourist {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        File file = new File("E:\\BigData_Learn\\IdeaProjects\\BigData\\HiveJDBC\\src\\data\\CityTourist.txt");
        //创建链接
        Connection conn = DriverManager.getConnection("jdbc:hive2://master:10000/dws");
        //加载Hive驱动
        Class.forName("org.apache.hive.jdbc.HiveDriver");
        //创建statement
        Statement stat = conn.createStatement();
        //执行SQL

        ResultSet rs = stat.executeQuery("select * from dws_city_tourist_msk_d where day_id='20180503'");

        String day_id="20180503";
        int cnt=0;
        while (rs.next()) {
            /*
            mdn string comment '手机号大写MD5加密'
            ,source_county_id string comment '游客来源区县'
            ,d_province_id string comment '旅游目的地省代码'
            ,d_stay_time double comment '游客在该省停留的时间长度（小时）'
            ,d_max_distance double comment '游客本次出游距离'
             */
            String mdn = rs.getString(1);
            String source_county_id = rs.getString(2);
            String d_province_id = rs.getString(3);
            double d_stay_time = rs.getDouble(4);
            double d_max_distance = rs.getDouble(5);
            String str = mdn + "," + source_county_id + "," + d_province_id + "," +
                    String.format("%.2f", d_stay_time) + "," + String.format("%.2f", d_max_distance) + "," + day_id + "\n";
            writeToFile(file, str);
            cnt++;

        }
        rs.close();
        stat.close();
        conn.close();
        System.out.println(cnt+"条数据写入成功!");

    }

    /**
     * 按行向文件中写数据
     *
     * @param file 目标文件位置
     * @param str  要写入的一行内容
     */
    public static void writeToFile(File file, String str) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(file, true);
            fw.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
